<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.3.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"example.com","root":"/","scheme":"Muse","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.json"};
  </script>

  <meta name="description" content="​        原文地址：https:&#x2F;&#x2F;blog.csdn.net&#x2F;m0_66881249&#x2F;article&#x2F;details&#x2F;128772180 继承​        继承可以使一个类能够使用被继承类的中的代码，即继承可以提高代码复用率，降低冗余性，提高开发效率。 ​        通俗来讲，通过继承，我们可以实现一个类中即使没有定义某一个方法，但是只有其父类中具有该方法，就可以实现正常的调用（">
<meta property="og:type" content="article">
<meta property="og:title" content="Python面向对象之继承">
<meta property="og:url" content="http://example.com/2023/11/11/Python%E9%9D%A2%E5%90%91%E5%AF%B9%E8%B1%A1%E4%B9%8B%E7%BB%A7%E6%89%BF/index.html">
<meta property="og:site_name" content="学无止境">
<meta property="og:description" content="​        原文地址：https:&#x2F;&#x2F;blog.csdn.net&#x2F;m0_66881249&#x2F;article&#x2F;details&#x2F;128772180 继承​        继承可以使一个类能够使用被继承类的中的代码，即继承可以提高代码复用率，降低冗余性，提高开发效率。 ​        通俗来讲，通过继承，我们可以实现一个类中即使没有定义某一个方法，但是只有其父类中具有该方法，就可以实现正常的调用（">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/202311112211229.png">
<meta property="og:image" content="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/202311112212963.png">
<meta property="article:published_time" content="2023-11-11T04:14:25.000Z">
<meta property="article:modified_time" content="2023-11-11T04:14:25.000Z">
<meta property="article:author" content="xudonglei">
<meta property="article:tag" content="python基础">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/202311112211229.png">

<link rel="canonical" href="http://example.com/2023/11/11/Python%E9%9D%A2%E5%90%91%E5%AF%B9%E8%B1%A1%E4%B9%8B%E7%BB%A7%E6%89%BF/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>Python面向对象之继承 | 学无止境</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">学无止境</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">Do not bb, show me the example</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-fw fa-home"></i>首页</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-fw fa-tags"></i>标签</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-fw fa-th"></i>分类</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-fw fa-archive"></i>归档</a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://example.com/2023/11/11/Python%E9%9D%A2%E5%90%91%E5%AF%B9%E8%B1%A1%E4%B9%8B%E7%BB%A7%E6%89%BF/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="xudonglei">
      <meta itemprop="description" content="搬砖 嵌入式">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="学无止境">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          Python面向对象之继承
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2023-11-11 12:14:25" itemprop="dateCreated datePublished" datetime="2023-11-11T12:14:25+08:00">2023-11-11</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/python/" itemprop="url" rel="index"><span itemprop="name">python</span></a>
                </span>
            </span>

          
            <span id="/2023/11/11/Python%E9%9D%A2%E5%90%91%E5%AF%B9%E8%B1%A1%E4%B9%8B%E7%BB%A7%E6%89%BF/" class="post-meta-item leancloud_visitors" data-flag-title="Python面向对象之继承" title="阅读次数">
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              <span class="post-meta-item-text">阅读次数：</span>
              <span class="leancloud-visitors-count"></span>
            </span>
  
  <span class="post-meta-item">
    
      <span class="post-meta-item-icon">
        <i class="fa fa-comment-o"></i>
      </span>
      <span class="post-meta-item-text">Valine：</span>
    
    <a title="valine" href="/2023/11/11/Python%E9%9D%A2%E5%90%91%E5%AF%B9%E8%B1%A1%E4%B9%8B%E7%BB%A7%E6%89%BF/#valine-comments" itemprop="discussionUrl">
      <span class="post-comments-count valine-comment-count" data-xid="/2023/11/11/Python%E9%9D%A2%E5%90%91%E5%AF%B9%E8%B1%A1%E4%B9%8B%E7%BB%A7%E6%89%BF/" itemprop="commentCount"></span>
    </a>
  </span>
  
  

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <p>​        原文地址：<a target="_blank" rel="noopener" href="https://blog.csdn.net/m0_66881249/article/details/128772180">https://blog.csdn.net/m0_66881249/article/details/128772180</a></p>
<h3 id="继承"><a href="#继承" class="headerlink" title="继承"></a>继承</h3><p>​        继承可以使一个类能够使用被继承类的中的代码，即继承可以提高代码复用率，降低冗余性，提高开发效率。</p>
<p>​        通俗来讲，通过继承，我们可以实现一个类中即使没有定义某一个方法，但是只有其父类中具有该方法，就可以实现正常的调用（调用的是父类中的那个方法），完成一定功能，这就是继承。</p>
<p>​        当类对象与类对象之间存在相同的内容，并满足子类对应的事物为父类对应事物中的一种时，就可以考虑使用继承，来提高代码复用性。</p>
<h3 id="Python中的继承"><a href="#Python中的继承" class="headerlink" title="Python中的继承"></a>Python中的继承</h3><p>​        Python是支持多继承的，而且Python2和Python3在继承这一块内容有区别，Python2中如果一个类没有对被继承的类进行指定（即下面代码这种情况），就是一个经典类（通俗来说就是比较老，默认没啥方法）</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">C</span>:</span></span><br><span class="line">    <span class="keyword">pass</span></span><br></pre></td></tr></table></figure>
<p>​        Python2中如果一个类对被继承的类进行了指定（即下面代码这种情况），就是一个新式类（通俗来讲就是具有一些比较NB的默认方法）</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">C</span>(<span class="params"><span class="built_in">object</span></span>):</span></span><br><span class="line">    <span class="keyword">pass</span></span><br></pre></td></tr></table></figure>
<p>​        但是，在Python3中，一个类如果没有进行指定，默认继承了object类，即Python3中已经去除了经典类，全部都是新式类（既然全部都是新式类了，那也就没必要说啥新式不新式的了，统一都叫做类），都具有NB的默认方法。<br>​        即下面这三种写法是等效的</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">C</span>:</span></span><br><span class="line">    <span class="keyword">pass</span></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">C</span>():</span></span><br><span class="line">    <span class="keyword">pass</span></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">C</span>(<span class="params"><span class="built_in">object</span></span>):</span></span><br><span class="line">    <span class="keyword">pass</span></span><br></pre></td></tr></table></figure>
<p>​        其实Python在使用类创建实例对象的时候，也是通过一个方法（名为: `_ <em>new</em> _ ）完成的，即没有这个方法，实例对象根本就不会被创建出来，而之前我直接在一点自定义类对象中写上pass，也可以创建实例对象成功，这其实就是因为，该类继承了object，而object类对象中是具有该方法的，于是进行实例化对象的时候，就会继承object类对象中的该方法，实现对象实例化，这就是继承机制发挥作用的一个案例。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">C</span>:</span></span><br><span class="line">    <span class="keyword">pass</span></span><br><span class="line"></span><br><span class="line">ins = C()</span><br><span class="line">print(ins)</span><br><span class="line"></span><br><span class="line"><span class="comment">#输出结果：&lt;__main__.C object at 0x000001EC9062AFD0&gt;</span></span><br></pre></td></tr></table></figure>
<h3 id="单继承"><a href="#单继承" class="headerlink" title="单继承"></a>单继承</h3><p>​        仅仅继承了一个类，代码中体现为一个类的括号中仅仅写了一个类名。</p>
<p>单继承的运作过程</p>
<p>​        对于一个类创建出来的实例对象，这个实例对象调用了实例方法，则解释器会先通过实例对象中的`_ _class__属性去寻找该实例对象的类中是否具有该方法（前面说过实例对象中是不存储方法id的，方法id都在类对象中）<br>​        如果没有，则通过该类中的类属性去寻找该类的父类中是否具有该方法，如果没有，则继续去寻找其父类，…最后如果在最顶层的object类中依旧没有找到，则抛出异常<br>​        在这一整个寻找过程中，在任意一个环节寻找到了同名的方法，则对该方法进行调用，并不再继续寻找下去。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">A</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">func</span>(<span class="params">self</span>):</span></span><br><span class="line">        print(self)</span><br><span class="line">        print(<span class="string">&#x27;A的func实例函数&#x27;</span>)</span><br><span class="line">   </span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">B</span>(<span class="params">A</span>):</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">func</span>(<span class="params">self</span>):</span></span><br><span class="line">        print(self)</span><br><span class="line">        print(<span class="string">&#x27;B的func实例函数&#x27;</span>)</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">C</span>(<span class="params">B</span>):</span></span><br><span class="line">    <span class="keyword">pass</span></span><br><span class="line">    </span><br><span class="line">ins = C()</span><br><span class="line">ins.func()</span><br><span class="line"></span><br><span class="line"><span class="comment">#输出结果：</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">&lt;__main__.C object at 0x00000275312FA6D0&gt;</span></span><br><span class="line"><span class="string">B的func实例函数</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br></pre></td></tr></table></figure>
<h3 id="多继承"><a href="#多继承" class="headerlink" title="多继承"></a>多继承</h3><p>继承了两个及两个以上的类，代码中体现为一个类的括号中写了多个类名，中间使用逗号隔开</p>
<p>多继承的运作过程</p>
<p>​        会按照该类括号中的父类的排列顺序，即从左到右逐个进行查找，针对每一个父类的查找可以参考单继承的查找方式，即先找到排列在第一个的父类中是否具有该方法，再寻找该父类的父类是否具有该方法…<br>​        如果第一个父类中都没有找到同名方法，则开始对第二个父类进行查找…如果从所有的父类那里都无法找到同名方法，则抛出异常<br>​        和单继承一样，在这一整个寻找过程中，在任意一个环节寻找找到了同名的方法，则对该方法进行调用，并不再继续寻找下去</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">A</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">func</span>(<span class="params">self</span>):</span></span><br><span class="line">        print(self)</span><br><span class="line">        print(<span class="string">&#x27;A的func实例函数&#x27;</span>)</span><br><span class="line">   </span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">B</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">func</span>(<span class="params">self</span>):</span></span><br><span class="line">        print(self)</span><br><span class="line">        print(<span class="string">&#x27;B的func实例函数&#x27;</span>)</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">C</span>(<span class="params">B,A</span>):</span></span><br><span class="line">    <span class="keyword">pass</span></span><br><span class="line">    </span><br><span class="line">ins = C()</span><br><span class="line">ins.func()</span><br><span class="line"></span><br><span class="line"><span class="comment">#输出结果：</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">&lt;__main__.C object at 0x000001A7DCDDAB20&gt;</span></span><br><span class="line"><span class="string">B的func实例函数</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br></pre></td></tr></table></figure>
<h3 id="方法重写"><a href="#方法重写" class="headerlink" title="方法重写"></a>方法重写</h3><p>​        如果子类对于继承自父类的某一个属性或者方法不满意，可以进行修改，而且即便对方法进行了修改，对父类及其他子类是没有任何影响的，即父类和父类的所有子类还是可以调用父类的原来的方法，仅仅就是本类和本类的子类的同名方法被修改了而已</p>
<p>​        其实从上面继承机制的角度来看方法重写，就比较好理解了，这就是利用继承的查找机制实现的嘛，根本就没有什么新东西，子类的方法被重写，就是子类创建了一个同名的方法，当子类和子类的实例对象调用该方法的时候，就会执行继承的查找机制，<strong>当查找到该子类空间的时候，此时就会发现这个同名的方法，就会立即调用该方法，而且不会去父类中继续查找</strong>，而针对父类和其他没有进行该方法重写的子类来说，没有进行方法重写，在继承查找过程中就还是会去调用父类中定义的方法，即沿用父类中的代码，这就是所谓的方法重写的本质</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">A</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">func</span>(<span class="params">self</span>):</span></span><br><span class="line">        print(self)</span><br><span class="line">        print(<span class="string">&#x27;A的func实例函数&#x27;</span>)</span><br><span class="line">   </span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">B</span>(<span class="params">A</span>):</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">func</span>(<span class="params">self</span>):</span></span><br><span class="line">        print(self)</span><br><span class="line">        print(<span class="string">&#x27;B重写后的func实例函数&#x27;</span>)</span><br><span class="line"></span><br><span class="line">    </span><br><span class="line">ins = B()</span><br><span class="line">ins.func()</span><br><span class="line"></span><br><span class="line"><span class="comment">#输出结果：</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">&lt;__main__.B object at 0x00000219992AACD0&gt;</span></span><br><span class="line"><span class="string">B重写后的func实例函数</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br></pre></td></tr></table></figure>
<p>​        我们经常对一个对象的__init__初始化方法进行方法重写<br>​        值得一提的是，其实Python中的运算符的计算就是通过调用类对象中的方法完成的，所以如果对这些与运算符对应的方法进行重写，就会导致运算机制发生改变，而这种通过重写方法来改变机制的过程，对于运算符来说，称为运算符重载</p>
<h3 id="super方法"><a href="#super方法" class="headerlink" title="super方法"></a>super方法</h3><p>​        很多情况下，父类的方法并不是完全没有利用价值，即可能在方法重写以后，依旧要调用父类的方法进行一个补充，而此时子类就可以使用super方法去调用父类中定义的任意方法，即使在该子类中该方法被重写过了。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">A</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">func</span>(<span class="params">self</span>):</span></span><br><span class="line">        print(self)</span><br><span class="line">        print(<span class="string">&#x27;A的func实例函数&#x27;</span>)</span><br><span class="line">   </span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">B</span>(<span class="params">A</span>):</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">func</span>(<span class="params">self</span>):</span></span><br><span class="line">        print(self)</span><br><span class="line">        <span class="built_in">super</span>().func()		<span class="comment">#使用super方法进行父类A的func实例对象的调用</span></span><br><span class="line">        print(<span class="string">&#x27;B重写后的func实例函数&#x27;</span>)</span><br><span class="line"></span><br><span class="line">    </span><br><span class="line">ins = B()</span><br><span class="line">ins.func()</span><br><span class="line"></span><br><span class="line"><span class="comment">#输出结果：</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">&lt;__main__.B object at 0x000001E7B544AB20&gt;</span></span><br><span class="line"><span class="string">&lt;__main__.B object at 0x000001E7B544AB20&gt;</span></span><br><span class="line"><span class="string">A的func实例函数</span></span><br><span class="line"><span class="string">B重写后的func实例函数</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br></pre></td></tr></table></figure>
<p>​        一个实例方法是可以使用类对象进行调用的，只不过，此时实例方法不会自动传入实参（即一个实例对象的引用），如果需要使用实例对象的话，我们要手动传入一个实例对象</p>
<p>​        其实上面这个使用super的代码和下面这个不使用super的代码是等效的</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">A</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">func</span>(<span class="params">self</span>):</span></span><br><span class="line">        print(self)</span><br><span class="line">        print(<span class="string">&#x27;A的func实例函数&#x27;</span>)</span><br><span class="line">   </span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">B</span>(<span class="params">A</span>):</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">func</span>(<span class="params">self</span>):</span></span><br><span class="line">        print(self)</span><br><span class="line">        A.func(self)        <span class="comment">#通过父类A直接调用其实例方法，注意要手动传入一个实例对象的引用</span></span><br><span class="line">        print(<span class="string">&#x27;B重写后的func实例函数&#x27;</span>)</span><br><span class="line"></span><br><span class="line">    </span><br><span class="line">ins = B()</span><br><span class="line">ins.func()</span><br><span class="line"></span><br><span class="line"><span class="comment">#输出结果：</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">&lt;__main__.B object at 0x0000015B33DFACD0&gt;</span></span><br><span class="line"><span class="string">&lt;__main__.B object at 0x0000015B33DFACD0&gt;</span></span><br><span class="line"><span class="string">A的func实例函数</span></span><br><span class="line"><span class="string">B重写后的func实例函数</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br></pre></td></tr></table></figure>
<p>​        super方法的妙处其实要在下面这个案例中得以体现:</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">parent</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">func</span>(<span class="params">self</span>):</span></span><br><span class="line">        print(<span class="string">&#x27;parent的func实例方法执行开始&#x27;</span>)</span><br><span class="line">        print(<span class="string">&#x27;parent的func实例方法执行完毕&#x27;</span>)</span><br><span class="line">   </span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">son1</span>(<span class="params">parent</span>):</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">func</span>(<span class="params">self</span>):</span></span><br><span class="line">        print(<span class="string">&#x27;son1重写后的func实例方法执行开始&#x27;</span>)</span><br><span class="line">        parent.func(self)</span><br><span class="line">        print(<span class="string">&#x27;son1重写后的func实例方法执行完毕&#x27;</span>)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">son2</span>(<span class="params">parent</span>):</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">func</span>(<span class="params">self</span>):</span></span><br><span class="line">        print(<span class="string">&#x27;son2重写后的func实例方法执行开始&#x27;</span>)</span><br><span class="line">        parent.func(self)</span><br><span class="line">        print(<span class="string">&#x27;son2重写后的func实例方法执行完毕&#x27;</span>)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">grandson</span>(<span class="params">son1, son2</span>):</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">func</span>(<span class="params">self</span>):</span></span><br><span class="line">        print(<span class="string">&#x27;grandson重写后的func实例方法执行开始&#x27;</span>)</span><br><span class="line">        son1.func(self)</span><br><span class="line">        son2.func(self)</span><br><span class="line">        print(<span class="string">&#x27;grandson重写后的func实例方法执行完毕&#x27;</span>)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">ins = grandson()</span><br><span class="line">ins.func()</span><br><span class="line"></span><br><span class="line"><span class="comment">#输出结果：</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">grandson重写后的func实例方法执行开始</span></span><br><span class="line"><span class="string">son1重写后的func实例方法执行开始</span></span><br><span class="line"><span class="string">parent的func实例方法执行开始</span></span><br><span class="line"><span class="string">parent的func实例方法执行完毕</span></span><br><span class="line"><span class="string">son1重写后的func实例方法执行完毕</span></span><br><span class="line"><span class="string">son2重写后的func实例方法执行开始</span></span><br><span class="line"><span class="string">parent的func实例方法执行开始</span></span><br><span class="line"><span class="string">parent的func实例方法执行完毕</span></span><br><span class="line"><span class="string">son2重写后的func实例方法执行完毕</span></span><br><span class="line"><span class="string">grandson重写后的func实例方法执行完毕</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br></pre></td></tr></table></figure>
<p>​        这个案例中的继承图如图所示，为一个钻石型的图案</p>
<img src="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/202311112211229.png" style="zoom:50%;">

<p>​        明显地，无论是仅仅看着代码进行分析，还是直接看打印结果，都可以分析出这么一个调用过程：</p>
<img src="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/202311112212963.png" style="zoom:70%;">

<p>​        明显，类对象parent中的func函数被调用了两次，想象一下这个过程中我们实际是要对一个数据进行一个初始化操作（在具体的项目中，确实很多时候就是要调用父类的方法进行属性的初始化操作），而且一般初始化要传入相应的参数的，比如看下面的简单的代码</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">parent</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span>(<span class="params">self, name</span>):</span></span><br><span class="line">        print(<span class="string">&#x27;parent的__init__方法执行开始&#x27;</span>)</span><br><span class="line">        self.name = name</span><br><span class="line">        print(<span class="string">&#x27;parent的__init__方法执行完毕&#x27;</span>)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">son</span>(<span class="params">parent</span>):</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span>(<span class="params">self, name</span>):</span></span><br><span class="line">        print(<span class="string">&#x27;son重写后的__init__方法执行开始&#x27;</span>)</span><br><span class="line">        parent.__init__(self, name)</span><br><span class="line">        print(<span class="string">&#x27;son重写后的__init__方法执行完毕&#x27;</span>)</span><br><span class="line"></span><br><span class="line">ins = son(<span class="string">&#x27;张三&#x27;</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment">#输出结果：</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">son重写后的__init__方法执行开始</span></span><br><span class="line"><span class="string">parent的__init__方法执行开始</span></span><br><span class="line"><span class="string">parent的__init__方法执行完毕</span></span><br><span class="line"><span class="string">son重写后的__init__方法执行完毕</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br></pre></td></tr></table></figure>
<p>​        如果将上面那个钻石型继承关系的代码中的所有实例方法 _ <em>func</em> _ <em>都改为上面这个传入参数的</em> <em>init</em> <em>方法，就可以想象，在grandson中调用父类son1的</em> <em>init__的参数是完全没有起到任何作用的，全部都在son2的</em> <em>init</em> <em>方法调用后被覆盖掉了，即第一次对于父类son1的</em> <em>init</em> <em>的调用完全是无效的<br>再者，进行调用</em> <em>init</em> <em>方法进行实例对象的初始化的时候（一般在</em> _ <em>init</em> <em>方法中，都会调用父类的</em> _ <em>init</em> <em>方法），最终的那个类的 _ _init</em> _方法被调用了两次，这也是很奇怪的事情不是吗</p>
<p>​        而super方法的使用就可以解决这个问题（即最终的那个类的 _ _init__方法被调用了两次，导致前一次调用的操作完全失效，是无用功的问题）</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">parent</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">func</span>(<span class="params">self</span>):</span></span><br><span class="line">        print(<span class="string">&#x27;parent的func实例方法执行开始&#x27;</span>)</span><br><span class="line">        print(<span class="string">&#x27;parent的func实例方法执行完毕&#x27;</span>)</span><br><span class="line">   </span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">son1</span>(<span class="params">parent</span>):</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">func</span>(<span class="params">self</span>):</span></span><br><span class="line">        print(<span class="string">&#x27;son1重写后的func实例方法执行开始&#x27;</span>)</span><br><span class="line">        <span class="built_in">super</span>().func()</span><br><span class="line">        print(<span class="string">&#x27;son1重写后的func实例方法执行完毕&#x27;</span>)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">son2</span>(<span class="params">parent</span>):</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">func</span>(<span class="params">self</span>):</span></span><br><span class="line">        print(<span class="string">&#x27;son2重写后的func实例方法执行开始&#x27;</span>)</span><br><span class="line">        <span class="built_in">super</span>().func()</span><br><span class="line">        print(<span class="string">&#x27;son2重写后的func实例方法执行完毕&#x27;</span>)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">grandson</span>(<span class="params">son1, son2</span>):</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">func</span>(<span class="params">self</span>):</span></span><br><span class="line">        print(<span class="string">&#x27;grandson重写后的func实例方法执行开始&#x27;</span>)</span><br><span class="line">        <span class="built_in">super</span>().func()</span><br><span class="line">        print(<span class="string">&#x27;grandson重写后的func实例方法执行完毕&#x27;</span>)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">ins = grandson()</span><br><span class="line">ins.func()</span><br><span class="line"></span><br><span class="line"><span class="comment">#输出结果：</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">grandson重写后的func实例方法执行开始</span></span><br><span class="line"><span class="string">son1重写后的func实例方法执行开始</span></span><br><span class="line"><span class="string">son2重写后的func实例方法执行开始</span></span><br><span class="line"><span class="string">parent的func实例方法执行开始</span></span><br><span class="line"><span class="string">parent的func实例方法执行完毕</span></span><br><span class="line"><span class="string">son2重写后的func实例方法执行完毕</span></span><br><span class="line"><span class="string">son1重写后的func实例方法执行完毕</span></span><br><span class="line"><span class="string">grandson重写后的func实例方法执行完毕</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br></pre></td></tr></table></figure>
<p>​        我知道读者看到这个结果大概率非常迷惑，但是至少我们可以发现一点，从输出结果来看，最终的那个类的 _ _init__方法只被调用了一次，非常符合我们的要求，即使用super方法貌似确实解决了我们上面的问题。</p>
<p>下面讲解super方法运行的原理</p>
<p>​        super使用的算法</p>
<p>​        使用super方法调用父类方法的时候，实际上会依据一个算法（即C3算法）自行计算出应该要调用哪一个父类的方法（从上面的输出结果来看，在调用son1的过程中调用了son2，所以实际上不一定是本类的父类）<br>​        实际上，我们不需要去理解C3算法的运行过程，只需要通过打印使用super方法的类对象的__mro__类属性即可知道super方法的调用顺序。</p>
<figure class="highlight"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">print(grandson.__mro__)</span><br><span class="line">(&lt;class &#x27;__main__.grandson&#x27;&gt;, &lt;class &#x27;__main__.son1&#x27;&gt;, &lt;class &#x27;__main__.son2&#x27;&gt;, &lt;class &#x27;__main__.parent&#x27;&gt;, &lt;class &#x27;object&#x27;&gt;)</span><br></pre></td></tr></table></figure>
<p>​        我们可以看到，这是一个元组类型对象，其中，每一个元素都是一个类对象<br>并且顺序依次为grandson、son1、son2、parent、object（明显为广度优先的查找原则）<br>对照上面代码的输出结果，我们惊奇地发现，每一次调用super. _ _init__方法，都是去调用该元组中的位于后面的类对象中的同名方法</p>
<p>​        实际上，类对象的 _ <em>mro</em> _类属性为一个元组（该元组也称为”作用链”），所有的元素都是类对象，super方法被调用的时候，会选择本类对象所在位置的后一个具有同名方法的类对象中的那个同名方法进行调用，如果执行代码的过程中，又遇到了一个super方法（无论和第一个super方法调用的方法名是否相同），则在原来的那个作用链中继续选择下一个类的同名方法进行调用，即后续所有的被嵌套调用的super方法，要选择调用哪个类对象的方法的时候，都要去查看调用第一个super方法的类对象的 _ _mro __ 类属性中各个类对象的排列顺序进行调用<br>​        接着我们康康super和 _ _mro__的官方定义</p>
<p>​        super被调用后，会返回一个对象，该对象是类的父类或兄弟类。super对于调用类中已被重写的父类方法非常用</p>
<p>​        类的 _ _mro__ 属性列出了getattr()和super()使用的搜索顺序。 _ _mro__属性是动态变化的，可以在继承层次结构更新时进行内容的变化</p>
<p>​        简单来说就是super方法的本质是使用类对象调用其中的同名方法，但是这个具体是哪一个类对象，要看 _ <em>mro__ 属性，</em> _ _mro __ 属性就是管这个事的，而且 _ _mro__属性是随着继承层次结构的变化而动态变化的。</p>
<p>​        其实super方法的返回的并不一定是 _ _mro__属性中本类的下一个类对象，严谨来说应该是下一个具有同名属性的类对象。</p>
<p>​        比如将上面那个代码中类对象son2的func函数的代码删除后的运行结果</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">parent</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">func</span>(<span class="params">self</span>):</span></span><br><span class="line">        print(<span class="string">&#x27;parent的func实例方法执行开始&#x27;</span>)</span><br><span class="line">        print(<span class="string">&#x27;parent的func实例方法执行完毕&#x27;</span>)</span><br><span class="line">   </span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">son1</span>(<span class="params">parent</span>):</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">func</span>(<span class="params">self</span>):</span></span><br><span class="line">        print(<span class="string">&#x27;son1重写后的func实例方法执行开始&#x27;</span>)</span><br><span class="line">        <span class="built_in">super</span>().func()</span><br><span class="line">        print(<span class="string">&#x27;son1重写后的func实例方法执行完毕&#x27;</span>)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">son2</span>(<span class="params">parent</span>):</span></span><br><span class="line">    <span class="keyword">pass</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">grandson</span>(<span class="params">son1, son2</span>):</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">func</span>(<span class="params">self</span>):</span></span><br><span class="line">        print(<span class="string">&#x27;grandson重写后的func实例方法执行开始&#x27;</span>)</span><br><span class="line">        <span class="built_in">super</span>().func()</span><br><span class="line">        print(<span class="string">&#x27;grandson重写后的func实例方法执行完毕&#x27;</span>)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">ins = grandson()</span><br><span class="line">print(grandson.__mro__)</span><br><span class="line">ins.func()</span><br><span class="line"></span><br><span class="line"><span class="comment">#输出结果：</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">(&lt;class &#x27;__main__.grandson&#x27;&gt;, &lt;class &#x27;__main__.son1&#x27;&gt;, &lt;class &#x27;__main__.son2&#x27;&gt;, &lt;class &#x27;__main__.parent&#x27;&gt;, &lt;class &#x27;object&#x27;&gt;)</span></span><br><span class="line"><span class="string">grandson重写后的func实例方法执行开始</span></span><br><span class="line"><span class="string">son1重写后的func实例方法执行开始</span></span><br><span class="line"><span class="string">parent的func实例方法执行开始</span></span><br><span class="line"><span class="string">parent的func实例方法执行完毕</span></span><br><span class="line"><span class="string">son1重写后的func实例方法执行完毕</span></span><br><span class="line"><span class="string">grandson重写后的func实例方法执行完毕</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br></pre></td></tr></table></figure>
<p>​        可以看到，grandson. _ _mro__的内容不变，但是在son1使用super方法的时候，并不是去调用son2的同名方法，而且son2中压根就没有这个名字的方法，于是son1会直接调用parent的同名方法</p>
<p>​        综上所述，super方法解决了在钻石型继承中父类方法最终会被调用多次，导致数据可能会被覆盖的问题。但是super方法的缺点在于，<strong>在多继承且为”钻石形继承”的情况下，写代码的时候，不知道最后在代码运行的时候，super方法使用的是哪一个类的方法（即代码的可读性差）</strong>；而且不同类的方法，形参数量极有可能不同，所以一般都会在调用super方法的时候全部写上不定长参数（即*args 与**kwargs）（进一步减低了代码的可读性）<br>​        当然，在单继承的情况下，super方法的使用不会有问题，而且可以明确知道super方法使用的是哪一个类的方法。</p>

    </div>

    
    
    

      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/python%E5%9F%BA%E7%A1%80/" rel="tag"># python基础</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2023/11/10/Python%E4%B8%ADclass,%20class()%E5%92%8Cclass(object)%E7%9A%84%E5%8C%BA%E5%88%AB/" rel="prev" title="Python中class, class()和class(object)的区别">
      <i class="fa fa-chevron-left"></i> Python中class, class()和class(object)的区别
    </a></div>
      <div class="post-nav-item">
    <a href="/2023/11/11/python%E9%87%8C%E7%9A%84super().__init__()%E6%9C%89%E4%BB%80%E4%B9%88%E4%BD%9C%E7%94%A8/" rel="next" title="python里的super().__init__()有什么作用">
      python里的super().__init__()有什么作用 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          
    <div class="comments" id="valine-comments"></div>

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E7%BB%A7%E6%89%BF"><span class="nav-number">1.</span> <span class="nav-text">继承</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Python%E4%B8%AD%E7%9A%84%E7%BB%A7%E6%89%BF"><span class="nav-number">2.</span> <span class="nav-text">Python中的继承</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%8D%95%E7%BB%A7%E6%89%BF"><span class="nav-number">3.</span> <span class="nav-text">单继承</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%A4%9A%E7%BB%A7%E6%89%BF"><span class="nav-number">4.</span> <span class="nav-text">多继承</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%96%B9%E6%B3%95%E9%87%8D%E5%86%99"><span class="nav-number">5.</span> <span class="nav-text">方法重写</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#super%E6%96%B9%E6%B3%95"><span class="nav-number">6.</span> <span class="nav-text">super方法</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">xudonglei</p>
  <div class="site-description" itemprop="description">搬砖 嵌入式</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">283</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">19</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">67</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2024</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">xudonglei</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://muse.theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Muse</a> 强力驱动
  </div>

        








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/muse.js"></script>


<script src="/js/next-boot.js"></script>




  




  
<script src="/js/local-search.js"></script>













  

  


<script>
NexT.utils.loadComments(document.querySelector('#valine-comments'), () => {
  NexT.utils.getScript('//unpkg.com/valine/dist/Valine.min.js', () => {
    var GUEST = ['nick', 'mail', 'link'];
    var guest = 'nick,mail,link';
    guest = guest.split(',').filter(item => {
      return GUEST.includes(item);
    });
    new Valine({
      el         : '#valine-comments',
      verify     : false,
      notify     : false,
      appId      : 'BT0Qw9HcTpPv1a6cT1iDBXKz-gzGzoHsz',
      appKey     : 'LMCMh8v02JTMFAwKNRcgoizI',
      placeholder: "Just go go",
      avatar     : 'mm',
      meta       : guest,
      pageSize   : '10' || 10,
      visitor    : true,
      lang       : 'zh-CN' || 'zh-cn',
      path       : location.pathname,
      recordIP   : false,
      serverURLs : ''
    });
  }, window.Valine);
});
</script>

</body>
</html>
